<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 职工代表大会编辑 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form @selectChange="selectChange" :formList="formList" :form="form" :editModel="editModel == 0 ? '' : ''" @selectOrg="selectOrg">
            <template v-slot:table>
              <a-form-model-item label=" " :colon="false">
                <!-- 表格 -->
                <s-table class="mb20" :highlightTitle='true' bordered ref="table1" tableLayout="fixed" size="default" rowKey="id" :columns="columns"  :data="loadData1" :alert="true" show-size-changer show-quick-jumper :showPagination="false">
                  <template v-for="col in ['notContainAddedTaxFee', 'addedTaxFee', 'containAddedTaxFee', 'remark']" :slot="col" slot-scope="text, record, index">
                    <div :key="col" class="form-item">
                      <template>
                        <template v-if="editModel != 0">
                          <BaseInput v-if="col === 'remark'" :class="col === 'remark' ? 'remark' : ''" :disabled="editModel == 0" v-model="record[col]"> </BaseInput>
                          <span v-else-if="col === 'containAddedTaxFee'">{{ text }} </span>

                          <BaseInputNumber v-else v-model="record[col]" :disabled="editModel == 0" :precision="2" @change="change1(index)" :constraintLength="[6,2]" :max="999999.99" :min="0"> </BaseInputNumber>
                          <!-- <BaseInputNumber v-else v-model="record[col]" :disabled="editModel == 0" :precision="2" @change="change1(index)"> </BaseInputNumber> -->
                        </template>
                        <template v-else> {{ text }}</template>
                      </template>
                    </div></template
                  >
                </s-table>
              </a-form-model-item>
            </template>

            <!-- 附件上传 -->
            <template #fileList>
              <template v-if="editModel != 0">
                <l-table businessCode="BM27" :uploadArrys.sync="form.fileList"></l-table>
                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
              </template>
              <file-link v-else :fileList="form.fileList" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
        <a-card>
          <title-name title="收款情况"></title-name>
          <custom-form :formList="formList1" :form="form" :editModel="editModel == 0 ? '' : ''"
            ><template v-slot:table>
              <!-- 表格 -->
              <s-table class="mb20" bordered  :highlightTitle='true' ref="table2" tableLayout="fixed" size="default" rowKey="id" :columns="columns" :data="loadData2" :alert="true" show-size-changer show-quick-jumper :showPagination="false">
                <template v-for="col in ['notContainAddedTaxFee', 'addedTaxFee', 'containAddedTaxFee', 'remark']" :slot="col" slot-scope="text, record, index">
                  <div :key="col" class="form-item">
                    <template>
                      <template v-if="editModel != 0">
                        <BaseInput v-if="col === 'remark'" :class="col === 'remark' ? 'remark' : ''" :disabled="editModel == 0" v-model="record[col]"> </BaseInput>
                        <span v-else-if="col === 'containAddedTaxFee'">{{ text }} </span>

                        <BaseInputNumber v-else v-model="record[col]" :disabled="editModel == 0" :precision="2" @change="change2(index)" :constraintLength="[6,2]" :max="999999.99" :min="0"> </BaseInputNumber>
                      </template>
                      <template v-else> {{ text }}</template>
                    </template>
                  </div></template
                ></s-table
              >
            </template></custom-form
          >
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="editModel != 0">
        <!-- <a-button class="button_right" v-if="id != '' && form.auditStatus == 'DRAFT'" type="danger" @click="handleRemove()"
                    >删除草稿</a-button
                > -->
        <a-button class="button_right" v-if="form.status == 'REJECTED'" type="primary" :loading="loadingBtn.REJECTED" @click="handleSubmit('REJECTED')">保存</a-button>
        <a-button v-else class="button_right" type="primary" :loading="loadingBtn.DRAFT" @click="handleSubmit('DRAFT')">保存草稿</a-button>
        <a-button class="button_right" type="primary" :loading="loadingBtn.SUBMITTED" @click="handleSubmit('SUBMITTED')">提交</a-button>
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
      <div class="btn_box page-btn-right-top" v-else>
        <a-button type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { getMeasureList, addMeasure, getMeasure } from '@/api/businessAffairs/lumpSumMeasurement'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import moment from 'moment'
const columns = [
  {
    title: '项目/金额',
    dataIndex: 'projectFeeStr'
  },
  {
  dataIndex: 'notContainAddedTaxFee',
    slots: { title: 'notContainAddedTaxFee' },
    scopedSlots: { customRender: 'notContainAddedTaxFee' },
    newTitle:'1.不含增值税',
    redTitle:'（万元）',
  },
  {
    dataIndex: 'addedTaxFee',
    slots: { title: 'addedTaxFee' },
    scopedSlots: { customRender: 'addedTaxFee' },
    newTitle:'2.增值税',
    redTitle:'（万元）',
  },
  {
    dataIndex: 'containAddedTaxFee',
    scopedSlots: { customRender: 'containAddedTaxFee' },
    slots: { title: 'containAddedTaxFee' },
    newTitle:'含增值税',
    redTitle:'（万元）',
    afterTitle:'（1+2）'
  },
  {
    title: '备注',
    dataIndex: 'remark',
    scopedSlots: { customRender: 'remark' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal
  },
  data() {
    this.columns = columns
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        projectId:null,
        measureDetailDefine: [
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '本月上报工程量（含过账甲指）',
            type: 1
          },
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '本月业主确权（含过账甲指）',
            type: 1
          },
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '本月业主确权（不含过账甲指）',
            type: 1
          },
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '本月实际产值（含过账甲指）',
            type: 1
          },
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '本月实际产值（不含过账甲指）',
            type: 1
          }
        ],

        measureDetailPay: [
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '合同约定应付金额（含过账甲指）',
            type: 2
          },
          {
            addedTaxFee: undefined,
            branchCompanyId: undefined,
            projectId: undefined,
            remark: undefined,
            curMonth: undefined,
            curYear: undefined,
            notContainAddedTaxFee: undefined,
            projectFeeStr: '实际付款金额（含过账甲指）',
            type: 2
          }
        ]
      }, // 表单
      id: '',
      loadData1: () => {
        if (this.form.measureDetailPay.length > 0) {
          return new Promise((resolve, reject) => {
            console.log('this.form.measureDetailDefinethis.form.measureDetailDefine')
            resolve({
              
              data: this.form.measureDetailDefine
            })
          })
        }
      },
      loadData2: () => {
        if (this.form.measureDetailPay.length > 0) {
          return new Promise((resolve, reject) => {
            resolve({
              data: this.form.measureDetailPay
            })
          })
        }
      },
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        contractPayTime: [{ required: true, message: '请输入' }],
        contractUpTime: [{ required: true, message: '请输入' }],
        factAuditTime: [{ required: true, message: '请输入' }],
        factPayTime: [{ required: true, message: '请输入' }],
        measureMonth: [{ required: true, message: '请选择' }],
        scheduleInfo: [{ required: true, message: '请输入' }],
        fileList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件

      disabledDateList: [],
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.fileList'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileList')
        })
      }
    },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    }
  },
  async mounted() {
    this.$route.meta.title = ['业主确权及实际产值 查看', '业主确权及实际产值 编辑', '业主确权及实际产值 新增'][this.editModel];
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_owner_confirmation_fact_value')

    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      getMeasure({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res[1].data;
          let measureDetailDefine = JSON.parse(JSON.stringify(this.form.measureDetailDefine)),
          measureDetailPay = JSON.parse(JSON.stringify(this.form.measureDetailPay)),
          newWeasureDetailPay = [],
          newMeasureDetailDefine = [];
          measureDetailDefine.length && measureDetailDefine.map((item)=>{
            if(item.projectFeeStr.trim()=='本月上报工程量（含过账甲指）'){
              newMeasureDetailDefine[0] = item;
            }else if(item.projectFeeStr.trim()=='本月业主确权（含过账甲指）'){
              newMeasureDetailDefine[1] = item;
            }else if(item.projectFeeStr.trim()=='本月业主确权（不含过账甲指）'){
              newMeasureDetailDefine[2] = item;
            }else if(item.projectFeeStr.trim()=='本月实际产值（含过账甲指）'){
              newMeasureDetailDefine[3] = item;
            }else if(item.projectFeeStr.trim()=='本月实际产值（不含过账甲指）'){
              newMeasureDetailDefine[4] = item;
            }
          })
          measureDetailPay.length && measureDetailPay.map((item)=>{
             if(item.projectFeeStr.trim()=='合同约定应付金额（含过账甲指）'){
              newWeasureDetailPay[0] = item;
               }else{
              newWeasureDetailPay[1] = item;
               }
          })
          this.form.measureDetailDefine = newMeasureDetailDefine
          this.form.measureDetailPay = newWeasureDetailPay
          this.$nextTick(() => {
            this.init = true
            this.$refs.table1.refresh(true)
            this.$refs.table2.refresh(true)
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.form.projectId = this.$userInfo().currentPost.projectId;
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
          {
              label: '所属单位',
              type: 'orgTree',
              keyName: 'projectId',
              rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
              span: 16,
              isAutoSelectFirst: true,
              isNeedAuth:true ,
              checkStrictly: true,
              disabled: true,
              viewName: "viewName",
          },
        // {
        //   type: SelectSubCompany,

        //   keyName: 'branchCompanyId',
        //   label: '分公司名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '项目名称',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchCompanyId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'measureMonth',
          type: 'a-month-picker',

          disabled: this.editModel == 0,
          label: '计量月份',
          attrs: {
            valueFormat: 'YYYY-MM',
            disabledDate: this.disabledDate
          }
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        },
        {
          keyName: 'scheduleInfo',
          type: 'BaseTextarea',
          label: '累计形象进度',
          disabled: this.editModel == 0,
          attrs: {
            maxLength: 3000
          },
          span: 24
        },
        {
          slot: true,
          keyName: 'fileList',
          label: '*附件上传',
          span: 24
        }
      ]
    },
    formList1() {
      return [
        {
          keyName: 'contractUpTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '合同约定每月上报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'factAuditTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '实际审批时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'contractPayTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '合同约定付款时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'factPayTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '实际付款时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24
        }
      ]
    }
  },
  methods: {
    //选择单位
    selectOrg(val) {
        if (val && val.length) {
            this.form.branchCompanyId = val[val.length - 2].orgId
        }
    },
    async selectChange(name, data) {
      if (name == 'projectId') {
        const [err, res] = await getMeasureList({ projectId: this.form.projectId })
        if (!err) {
          console.log(res)
          this.disabledDateList = res.data
        }
      }
    },
    disabledDate(current) {
      let flag = false
      this.disabledDateList.forEach((i) => {
        if ((i.status == 'PAST' || i.status == 'SUBMITTED') && moment(current).format('YYYY-MM') == i.measureMonth) {
          flag = true
        }
      })

      return flag
    },
    /**
     * 输入框事件
     */
    change1(index) {    
      this.measureDetailDefineIndex = index
      if (
        typeof this.form.measureDetailDefine[index].addedTaxFee === 'number' && (this.form.measureDetailDefine[index].addedTaxFee || this.form.measureDetailDefine[index].addedTaxFee == 0) &&
        typeof this.form.measureDetailDefine[index].notContainAddedTaxFee === 'number' && (this.form.measureDetailDefine[index].notContainAddedTaxFee || this.form.measureDetailDefine[index].notContainAddedTaxFee == 0)
      ) {
          this.form.measureDetailDefine[index].containAddedTaxFee = (this.form.measureDetailDefine[index].addedTaxFee + this.form.measureDetailDefine[index].notContainAddedTaxFee).toFixed(2)
          this.$forceUpdate();
      }
    },
    change2(index) {
      if (
        typeof this.form.measureDetailPay[index].addedTaxFee === 'number' && (this.form.measureDetailPay[index].addedTaxFee || this.form.measureDetailPay[index].addedTaxFee == 0) &&
        typeof this.form.measureDetailPay[index].notContainAddedTaxFee === 'number' && (this.form.measureDetailPay[index].notContainAddedTaxFee || this.form.measureDetailPay[index].notContainAddedTaxFee == 0)
      ) {
        this.$nextTick(() => {
          this.form.measureDetailPay[index].containAddedTaxFee = (this.form.measureDetailPay[index].addedTaxFee + this.form.measureDetailPay[index].notContainAddedTaxFee).toFixed(2)
          this.$forceUpdate();
        })
      }
    },

    addtableInfo(list) {
      list.forEach((item) => {
        item.branchCompanyId = this.form.branchCompanyId
        item.projectId = this.form.projectId
        item.curMonth = this.form.measureMonth?.slice(-2)
        item.curYear = this.form.measureMonth?.slice(0, 4)
      })
      return list
    },
    validateTable(list) {
      let flag = false

      list.forEach((item) => {
        if ((!item.notContainAddedTaxFee && item.notContainAddedTaxFee != 0) || (!item.addedTaxFee && item.addedTaxFee != 0)) {
          flag = true
        }
      })
      if (flag) {
        this.$message.warning('请完善表格后提交')
      }
      return flag
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
    /**
     * 提交表单
     */
    async handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED') {
        // 校验表单
        if (!this.validateForm() || this.validateTable(this.form.measureDetailPay) || this.validateTable(this.form.measureDetailDefine)) {
          return
        }
      }

      if(!this.form.measureMonth) {
        this.$message.warn("请填写计量月份")
        return
      }

      this.loading = true
      this.loadingBtn[status] = true
      this.form.status = status
      let form = this.$clone(this.form)
      form.measureDetailPay = []
      form.measureDetailDefine = []
      form.measureDetailPay = this.addtableInfo(this.form.measureDetailPay)
      form.measureDetailDefine = this.addtableInfo(this.form.measureDetailDefine)
      this.submitApprovalConfirm(status == 'SUBMITTED'?this.processConfig:6,async (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      const [err, res] = await addMeasure(form)
      console.log(res)
      this.loading = false
      this.loadingBtn[status] = false
      if (!err) {
        this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
            if(status =='SUBMITTED') {
              //提交时，返回id
                  this.businessId = res.data.id || this.id ;
                  this.setProcessConfig = this.processConfig;
                  return
              }else{
                  this.$multiTab.close()
              }
      } else {
        this.$message.warning(res.msg)
      }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
